package com.ecloud.gateway.filter;

import java.util.List;
import java.util.Locale;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import com.ecloud.gateway.global.GlobalConfig;

import reactor.core.publisher.Mono;

/**
 * 国际化过滤器 用于设置客户端语言环境
 *
 * @author LiuGangQiang Create in 2021/03/25
 */
@Configuration
public class LocaleFilter implements GlobalFilter, Ordered {

    /**
     * @see org.springframework.core.Ordered#getOrder()
     */
    @Override
    public int getOrder() {
        return GlobalConfig.LOCALE_FILTER_ORDER;
    }

    /**
     * @see org.springframework.cloud.gateway.filter.GlobalFilter#filter(org.springframework.web.server.ServerWebExchange, org.springframework.cloud.gateway.filter.GatewayFilterChain)
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /* 调用方法之前调用 */
        ServerHttpRequest request = exchange.getRequest();
        request = request.mutate().headers(header -> {
            /* 获取语言列表 */
            List<Locale> locales = header.getAcceptLanguageAsLocales();
            /* 设置上下文语言 */
            if (locales != null && locales.size() > 0) {
                /* 默认取第一个语言作为默认环境 */
                LocaleContextHolder.setDefaultLocale(locales.get(0));
            } else {
                /* 如果不存在语言标头则默认采用中文环境 */
                LocaleContextHolder.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
            }
        }).build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        /* 向下传递 */
        return chain.filter(build);
    }
}
